<template>
  <div id="areaDiv">
    <div class="tableDiv">
      <div class="header">

      </div>
      <div class="body">
        <div id="insertDiv">
          <div>
            <Form ref="lightAdd" :label-width="120">
              <FormItem prop="userRole">
                <Select v-model="roleId" @on-select="roleChange" style="width: 20em">
                  <Option v-for="item in roleList" v-if="item.isRoot==0" :value="item.pkid" :key="item.pkid">{{ item.roleName }}</Option>
                </Select>
                <Button class="buttonDiv addButton" type="warning" icon="md-add" @click="insertMsg">添加</Button>
                <Button class="buttonDiv addButton" type="primary" icon="md-create" @click="updateMsg">修改</Button>
                <Button class="buttonDiv addButton" type="error" icon="md-close" @click="deleteMsg">删除</Button>
              </FormItem>
              <FormItem label="对应权限：">
                <div>
                  <span v-for="(item,index) in moduleList" :key="index">
                    <Button
                      class="moduleButton"
                      type="success"
                      icon="md-checkmark"
                      ghost
                      v-if="item.own==1"
                      @click="moduleDelete(item)"
                    >{{item.moduleName}}</Button>

                    <Button
                      class="moduleButton"
                      type="primary"
                      icon="md-radio-button-off"
                      ghost
                      v-else
                      @click="moduleAdd(item)"
                    >{{item.moduleName}}</Button>
                  </span>
                </div>
              </FormItem>
            </Form>
          </div>

          <div class="formButtonDiv">
<!--            <Button class="buttonDiv" @click="$router.go(-1);">返回</Button>-->
<!--            <Button class="buttonDiv" type="primary">提交</Button>-->
          </div>
        </div>
      </div>
      <div class="footer">
        <div class="commonFooterBtn">

        </div>
        <div class="commonFooterPage">

        </div>
      </div>
      <Modal
        v-model="addModal"
        @on-cancel="cancalTableForm('addMsg')"
      >
        <div class="userModalHeader" slot="header">
          <span>添加</span>
        </div>
        <div>
          <Form :model="formModal" ref="addMsg" :rules="formMsgRule" :label-width="100">
            <FormItem label="角色：" prop="roleName">
              <Input v-model="formModal.roleName" placeholder="请输入新增角色"/>
            </FormItem>
          </Form>
        </div>
        <div slot="footer" class="userModalFooter">
          <Button icon="" type="default" @click="addModal=false;cancalTableForm('addMsg')">取消</Button>
          <Button icon="" type="primary" @click="submitAdd">保存</Button>
        </div>
      </Modal>
      <!--修改框-->
      <Modal
        v-model="updateModal"
        @on-cancel="cancalTableForm('updateMsg')"
      >
        <div class="modalHeader" slot="header">
          <span>修改</span>
        </div>
        <div>
          <Form :model="formModal" ref="updateMsg" :rules="formMsgRule" :label-width="100">
            <FormItem label="角色：" prop="roleName">
              <Input v-model="formModal.roleName" placeholder="请输入新增角色"/>
            </FormItem>
          </Form>
        </div>
        <div slot="footer" class="userModalFooter">
          <Button icon="" type="default" @click="updateModal=false;cancalTableForm('updateMsg')">取消</Button>
          <Button icon="" type="primary" @click="updateSubmit">保存</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
  import { mapState, mapMutations } from "vuex";
  export default {
    name: "index",
    data(){
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写角色'));
        } else {
          this.$app.post('/trole/examineRole', {
            roleName:value
          }).then((res)=>{
            if(res.data.code==0){
              callback();
            }else{
              callback(new Error('重复角色'));
            }
            // console.log(res);
          }).catch((res)=>{
            //console.log(response);
          });

        }
      };
      return{
        addModal:false,
        updateModal:false,
        formModal:{
          pkid:0,
          roleName:'',
        },
        formMsgRule: {
          roleName: [
            {required: true, message: '请输入角色', trigger: 'blur'},
            { validator: validatePass, trigger: "blur" },
          ],
        },
        roleId:1,//角色Id
        roleList:[
          // {isRoot: 1, pkid: 1, roleCode: "root", roleName: "系统管理员"},
          // {isRoot: 0, pkid: 2, roleCode: "admin1", roleName: "管理员1"},
          // {isRoot: 0, pkid: 3, roleCode: "admin2", roleName: "管理员2"}
        ],
        roleModuleList:[

        ],//当前角色拥有权限
        // own =1代表有此权限
        moduleList:[
          // {"moduleName": "管理员列表","moduleNo": "adminList","moduleStatus": "1","pkid": 1,"own":0},
          // {"moduleName": "管理员添加","moduleNo": "adminInsert","moduleStatus": "0","pkid": 2,"own":1},
          // {"moduleName": "管理员修改","moduleNo": "adminUpdate","moduleStatus": "1","pkid": 3,"own":1},
          // {"moduleName": "测试模块","moduleNo": "test","moduleStatus": "1","pkid": 5,"own":1},
          // {"moduleName": "测块","moduleNo": "test","moduleStatus": "1","pkid": 6,"own":1},
          // {"moduleName": "管理员列表","moduleNo": "adminList","moduleStatus": "1","pkid": 1,"own":1},
          // {"moduleName": "1","moduleNo": "adminInsert","moduleStatus": "0","pkid": 2,"own":1},
          // {"moduleName": "管理员修改","moduleNo": "adminUpdate","moduleStatus": "1","pkid": 3,"own":1},
          // {"moduleName": "测试模块","moduleNo": "test","moduleStatus": "1","pkid": 5,"own":1},
          // {"moduleName": "测试模块","moduleNo": "test","moduleStatus": "1","pkid": 6,"own":1},
          // {"moduleName": "管理员列表","moduleNo": "adminList","moduleStatus": "1","pkid": 1,"own":1},
          // {"moduleName": "管理员添加","moduleNo": "adminInsert","moduleStatus": "0","pkid": 2,"own":1},
          // {"moduleName": "管理员修改","moduleNo": "adminUpdate","moduleStatus": "1","pkid": 3,"own":1},
          // {"moduleName": "测试模块","moduleNo": "test","moduleStatus": "1","pkid": 5,"own":1},
          // {"moduleName": "测试","moduleNo": "test","moduleStatus": "1","pkid": 6,"own":1},
        ],
      }
    },
    computed: {
      ...mapState({ modulesArr: state => state.app.modulesArr })
    },
    methods:{
      cancalTableForm(name){
        // this.formItem.deviceID = null;
        this.$refs[name].resetFields();
      },
      deleteMsg(){
        let that=this;
        return new Promise((resolve, reject) => {
          this.$app.post('/trole/deleteRole', {
            pkids:[that.roleId],
          }).then((res)=> {
            if (res.data.code == 0) {
              that.$Message.success("删除成功");
              that.init();
            }else{
              that.$Message.error("删除失败");
            }
          })
        })
      },
      updateMsg(){
        this.updateModal=true;
        let that=this;
        let item=this.roleList.find((item)=>{
          return (item.pkid == that.roleId)
        })
        this.formModal=JSON.parse(JSON.stringify(item));
      },
      insertMsg(){
        this.addModal=true;
      },
      //修改提交
      updateSubmit(){
        let that=this;
        return new Promise((resolve, reject) => {
          this.$app.post('/trole/updateRole', {
            pkid:that.formModal.pkid,
            roleName:that.formModal.roleName,
          }).then((res)=>{
            if(res.data.code==0){
              that.updateModal=false;

              that.$Message.success("修改成功");
              that.init(that.formModal.pkid);
              that.cancalTableForm('updateMsg')
            }else{
              that.$Message.error("修改失败");
            }
          }).catch((res)=>{reject(res)})
        })
      },
      //添加提交
      submitAdd(){
        let that=this;
        this.$refs["addMsg"].validate(valid => {
          if (valid) {
            return new Promise((resolve, reject) => {
              this.$app.post('/trole/addRole', {
                roleName:that.formModal.roleName,
              }).then((res)=>{
                if(res.data.code==0){
                  that.addModal=false;

                  that.$Message.success("添加成功");
                  that.init(res.data.data);
                  that.cancalTableForm('addMsg');
                }else{
                  that.$Message.error("添加失败");
                }
              }).catch((res)=>{reject(res)})
            })
          }
        })

      },
      //赋予权限
      moduleAdd(item){
        // console.log("给：",this.roleId,"赋予：",item);
        var that=this;
        return new Promise(resolve => {
            this.$app.post('/trole/giveModuleByRole', {
              roleId:that.roleId,
              moduleId:item.pkid,
            }).then((res)=>{
              if(res.data.code==0){
                that.roleChange();
                that.$Message.success("赋权成功");
              }else{
                that.$Message.error("赋权失败");
              }
            })
        })
      },
      //收回权限
      moduleDelete(item){
        // console.log("给：",this.roleId,"收回：",item);
        var that=this;
        return new Promise(resolve => {
          this.$app.post('/trole/takeBackModuleByRole', {
            roleId:that.roleId,
            moduleId:item.pkid,
          }).then((res)=>{
            if(res.data.code==0){
              that.roleChange();
              that.$Message.success("收回成功");
            }else{
              that.$Message.error("收回失败");
            }
          })
        })
      },
      roleChange(tag){
        if(tag){
          this.roleId=tag.value;
        }
        // console.log("选择：：",tag.value,this.roleId)
        let that=this;
        return new Promise(resolve => {
          this.$app.post('/trole/getAllModuleNoByRoleId', {
            roleId:that.roleId
          }).then((res)=>{
            if(res.data.code==0){
              // console.log("角色对应模块：：：",res.data.data);
              that.roleModuleList=res.data.data;


              that.getAllModules();
              resolve();
            }else{
              that.$Message.error("获取管理员角色失败");
            }
          })
        })
      },
      getAllModules(){
        let that=this;
        return new Promise(resolve => {
          this.$app.post('/tmodule/getAllModule', {}).then((res)=>{
            if(res.data.code==0){
              // console.log(res.data.data.list);
              let allModule=res.data.data.list;
              allModule.forEach((item,index)=>{
                if(that.roleModuleList.indexOf(item.moduleNo)<0){
                  item.own=0
                }else{
                  item.own=1
                }
              });

              // console.log(allModule);
              that.moduleList=allModule;
              resolve();
            }else{
              that.$Message.error("获取管理员角色失败");
            }
          })
        })
      },
      getAllRoleList(roleId){
        let that=this;
        return new Promise(resolve => {
          this.$app.post('/trole/getAllRole', {}).then((res)=>{
            if(res.data.code==0){
              let resultList=res.data.data.list;
              resultList.forEach((item,index)=>{
                if(item.isRoot==1){
                  resultList.splice(index, 1)
                }
              });
              that.roleList=resultList;

              if(roleId){
                that.roleId=roleId;
              }else{
                that.roleId=resultList[0].pkid;
              }
              resolve();
            }else{
              that.$Message.error("获取管理员角色失败");
            }
          })
        })
      },
      init(roleId){
        let that=this;
        return new Promise((resolve, reject) => {
          this.getAllRoleList(roleId).then(()=>{
            that.roleChange().then(()=>{
              resolve();
            })
          });
        })

      }
    },
    mounted() {
      this.init();
    }
  }
</script>

<style lang="less" scoped>
  .tableDiv{
    height: 100%;
  }
  #areaDiv{
    width: 100%;
    height: 100%;

    #insertDiv{
      width: 60%;
      margin: 0 auto;
      padding-top: 10em;

      .formButtonDiv{
        float: right;
        & .buttonDiv{
          /*margin: 0 .5em;*/
        }
      }
    }

    .moduleButton{
      margin: 0 .5em .5em 0;
    }
  }
</style>
